package models;

import java.util.List;
import java.util.Set;

import javax.persistence.Entity;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;

import play.db.jpa.Model;
import play.libs.Crypto;
import client.RepositoryDTO;

@Entity
@NamedQuery(name="Repository.findEnabled", query="from Repository r where r.enabled=true")
public class Repository extends Model {
	
	public String name;
	
	public String url;
	
	public String username;
	public String password;
	
	public boolean enabled = true;
	
	@OneToMany
	public Set<Revision> revisions;

	public long lastRevision = 0;
	
	public long lastRevisionInRepository = 0;

	public static List<Repository> findAllEnabled() {
		return em().createNamedQuery("Repository.findEnabled").getResultList();
	}

	public static RepositoryDTO convertToDTO(Repository r) {
		final RepositoryDTO returnDTO = new RepositoryDTO();
		returnDTO.setName(r.name);
		returnDTO.setEnabled(r.enabled);
		returnDTO.setId(r.id);
		returnDTO.setUrl(r.url);
		returnDTO.setUsername(r.username);
		returnDTO.setPassword("****");
		return returnDTO;
	}

	public static Repository convertFromDTO(RepositoryDTO repositoryDTO) {
		final Repository repository = new Repository();
		if (repositoryDTO.getId()>0) {
			repository.id = repositoryDTO.getId();
		}
		repository.name = repositoryDTO.getName();
		repository.url = repositoryDTO.getUrl();
		repository.username = repositoryDTO.getUsername();
		repository.password = Crypto.encryptAES(repositoryDTO.getPassword());
		return repository;
	}
}